
const path = require('path');
const fs = require('fs').promises;
// 配置 - 设置要扫描的根目录
const ROOT_DIR = path.join(process.cwd(), './sampledata'); // 可以修改为任何目录

// 递归获取文件夹结构
async function getFolderStructure(dirPath, relativePath = '') {
  try {
    const items = await fs.readdir(dirPath, { withFileTypes: true });
    const structure = [];
    
    for (const item of items) {
      if (item.isDirectory()) {
        const fullPath = path.join(dirPath, item.name);
        const itemRelativePath = path.join(relativePath, item.name);
        
        // 获取子目录结构
        const children = await getFolderStructure(fullPath, itemRelativePath);
        
        structure.push({
          name: item.name,
          path: itemRelativePath,
          children: children
        });
      }
    }
    
    // 按名称排序
    structure.sort((a, b) => a.name.localeCompare(b.name));
    
    return structure;
  } catch (error) {
    console.error(`Error reading directory ${dirPath}:`, error);
    return [];
  }
}




let fileselect = async (ctx) => {
try {
    // 确保根目录存在
    try {
      await fs.access(ROOT_DIR);
    } catch (err) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: `根目录不存在: ${ROOT_DIR}`
      };
      return;
    }
    
    const structure = await getFolderStructure(ROOT_DIR);
    
    ctx.body = {
      success: true,
      basePath: ROOT_DIR,
      structure: structure
    };
    
  } catch (error) {
    console.error('Error generating folder structure:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '生成文件夹结构失败',
      error: error.message
    };
  }
}

exports.fileselect = fileselect
